package com.siashan.unipay4j.wx.splitbill;

import com.alibaba.fastjson.JSON;
import com.siashan.unipay4j.core.Result;
import com.siashan.unipay4j.core.UnipayConst;
import com.siashan.unipay4j.core.splitbill.ISplitBillRelationUnbind;
import com.siashan.unipay4j.core.splitbill.UnBindModel;
import com.siashan.unipay4j.wx.AbstractWxPay;
import com.siashan.unipay4j.wx.WxBizEnum;
import com.siashan.unipay4j.wx.sdk.WXPayConstants;
import lombok.extern.slf4j.Slf4j;

import java.util.HashMap;
import java.util.Map;

/**
 * 删除分账请求方
 *
 * @author siashan
 * @since V1.0.1
 **/
@Slf4j
public class WxPaySplitBillRelationUnBind extends AbstractWxPay implements ISplitBillRelationUnbind {
    @Override
    public Result unbind(UnBindModel model) {
        log.info("WxPaySplitBill => 订单{} 微信分账接收方解绑请求到达", model.getOutTradeNo());
        try {
            Map<String, String> r = initWxPay().sendRequest(wrapParam(model), WXPayConstants.PAY_PROFITSHARINGADDRECEIVER_URL_SUFFIX, WxBizEnum.SPLITBILL, true);
            log.info("WxPaySplitBill => 订单{} 微信分账接收方解绑请求返回报文:{}", model.getOutTradeNo(),r);
            String returnCode = getReturnCode(r);
            if (isReturnSuccess(returnCode)) {
                if (isResultSuccess(r)) {
                    log.info("WxPaySplitBill => 订单{} 微信分账接收方解绑请求成功", model.getOutTradeNo());
                    return Result.tradeSuccess(r);
                } else {
                    String errCode = r.get(WXPayConstants.ERR_CODE);
                    String errCodeDes = r.get(WXPayConstants.ERR_CODE_DES);
                    return Result.returnFail(errCode, errCodeDes);
                }
            } else {
                String returnMsg = r.get(WXPayConstants.RETURN_MSG);
                return Result.returnFail(returnCode, returnMsg);
            }

        } catch (Exception e) {

        }
        return Result.exception();
    }

    private Map<String, String> wrapParam(UnBindModel model) {
        Map<String, String> map = new HashMap<>();
        Map<String, String> receiver = new HashMap<>();
        receiver.put("type", model.getType());
        receiver.put("account", model.getAccount());
        map.put("receiver", JSON.toJSONString(receiver));
        return map;
    }
}
